package com.study.netty.demo1;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * netty 服务端
 *
 * @author wuxj
 */
public class ServerDeme {

    public static ChannelHandlerContext channelHandlerContext = null;

    public static void start(int port) {

        // 创建两个线程池，在此可看成一个黑盒，在下篇文章中会介绍到
        EventLoopGroup bossEventLoop = new NioEventLoopGroup(1);
        EventLoopGroup workerEventLoop = new NioEventLoopGroup();

        try {
            // 服务端启动引导类
            ServerBootstrap bootstrap = new ServerBootstrap();
            // 设置线程池
            bootstrap.group(bossEventLoop, workerEventLoop)
                    // 设置服务端channel
                    .channel(NioServerSocketChannel.class)
                    // 设置一个处理客户端channel的handler
                    .childHandler(new ChannelInitializer() {
                        @Override
                        protected void initChannel(Channel ch) {
                            ch.pipeline().addLast(new SimpleServerHandler());
                        }
                    });

            // 绑定端口
            ChannelFuture channelFuture = bootstrap.bind(port).sync();
            // 阻塞在此，直到被关闭
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 优雅关闭资源
            bossEventLoop.shutdownGracefully();
            workerEventLoop.shutdownGracefully();
        }
    }
}
